package com.cyf.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.cyf.app.network.bean.AppBusinessReq;
import com.cyf.app.network.bean.AppBusinessRsp;
import com.cyf.app.network.bean.car.AppAdCarReq;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.merchat.network.bean.MerchantBusinessRsp;
import com.cyf.merchat.network.bean.MerchantCouponVo;
import com.cyf.merchat.network.bean.UserIssueRecordReq;
import com.cyf.service.AppUserCarService;
import com.cyf.service.CheckParam;
import com.cyf.util.*;
import com.cyf.wechat.network.bean.*;
import com.cyf.wechat.service.WechatApiService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class WechatApiServiceImpl implements WechatApiService {

    @Resource
    private RegSmsMapper regSmsMapper;
    @Resource
    private AppCarMapper appCarMapper;
    @Resource
    private WeChatSubscriptionUtil weChatSubscriptionUtil;
    @Resource
    private AppUserPayMaper appUserPayMaper;
    @Resource
    private UsersWechatMapper usersWechatMapper;
    @Resource
    private AppUserCarMapper appUserCarMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private InParkingMapper inParkingMapper;
    @Resource
    private AppUserCarService appUserCarService;
    @Resource
    private MerchantCouponMapper merchantCouponMapper;
    @Resource
    private FeeGroupMapper feeGroupMapper;
    @Resource
    private InOutParkingMapper inOutParkingMapper;
    @Resource
    private CheckParam checkParam;
    @Resource
    private PiaoTongMapper piaoTongMapper;
    @Resource
    private FeeDetailMapper feeDetailMapper;
    @Resource
    private UserInvoiceMapper userInvoiceMapper;
    @Resource
    private CarMapper carMapper;
    @Resource
    private PersonMapper personMapper;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private ParkingMapper parkingMapper;
    @Autowired
    private PayOrderMergeMapper payOrderMergeMapper;

    private final String token = "cheyifu1qaz2wsx";
    private final String GETFEE_URL = "http://www.cheyifu2016.com:8892/openapi/getFee";


    @Override
    @Transactional
    public WechatRegRsp login(LoginAppReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        RegSms rsgSms = regSmsMapper.getByMobile(req.getMobile());
        if (rsgSms == null) {
             rsp.setStrError("验证码已超时");
             return rsp;
         }
         if (!(rsgSms.getCode()).equals(req.getSmsCode())) {
             rsp.setStrError("验证码不正确");
             return rsp;
         }
         //根据手机号获取用户信息
        User user = userMapper.getByMobile(req.getMobile());
        if (user == null) {
            user = new User();
            user.setCreatedTime(new Date());
            user.setMobile(req.getMobile());
            userMapper.insertUser(user);
        }
        //UsersWechat usersWechat = usersWechatMapper.getByPhone(req.getMobile());
        UsersWechat usersWechat = usersWechatMapper.selectlistByUserId(user.getId());
        if(usersWechat==null){
            usersWechat = new UsersWechat();
            //新用户注册
            //当用户前端获取code成功后，获取用户微信信息
            GetOpenidRsp getOpenidRsp = weChatSubscriptionUtil.getOpenid(req.getCode());
            if (getOpenidRsp.getOpenid() == null) {
                //获取token 失败!
                log.error("获取openid失败:{}", getOpenidRsp.getErrmsg());
                rsp.setResult(AppBusinessRsp.FAIL);
                rsp.setStrError("获取用户openid失败!");
                return rsp;
            }
            GetWechatInfoRsp wechatInfoRsp = weChatSubscriptionUtil.getWechatInfo(getOpenidRsp.getOpenid());
            usersWechat.setApiUserId(0);
            usersWechat.setUserId(user.getId());
            usersWechat.setOpenid(getOpenidRsp.getOpenid());
            usersWechat.setParkingId(0);
            usersWechat.setLocalPersonId(0);
            String personName = null;
            if(wechatInfoRsp.getNickname()!=null){
                personName = EmojiFilter.filterEmoji(wechatInfoRsp.getNickname());
            }
            usersWechat.setPersonName(personName);
            usersWechat.setHeadImgurl(wechatInfoRsp.getHeadimgurl());
            usersWechat.setPhone(req.getMobile());
            usersWechat.setCreateTime(new Date());
            usersWechatMapper.insert(usersWechat);
            rsp.setOpenid(getOpenidRsp.getOpenid());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setPhone(req.getMobile());
        }else {
            //手机号为空时更新手机号
            if(StringUtils.isBlank(usersWechat.getPhone())){
                try {
                    usersWechatMapper.updateUserWechat(req.getMobile(),new Date(),usersWechat.getId());
                } catch (Exception e) {

                }
            }
            rsp.setOpenid(usersWechat.getOpenid());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setPhone(req.getMobile());
        }
        regSmsMapper.deleteByMobile(req.getMobile());
        return rsp;
    }

    @Override
    public WechatRegRsp addCar(AppAdCarReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            if(StringUtils.isBlank(req.getPlate())){
                rsp.setStrError("参数不能为空!");
                return rsp;
            }
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(usersWechat.getUserId());
            if(appCars!=null){
                for(AppCar c:appCars){
                    if(req.getPlate().equals(c.getPlate())){
                        rsp.setStrError("您已经添加过该车辆!");
                        return rsp;
                    }
                }
            }
            AppCar c =  appCarMapper.getByPlate(req.getPlate());
            if(c!=null){
               String mobile = appCarMapper.getPlateByMobile(c.getId());
               if(mobile!=null){
                   String phone = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
                   rsp.setStrError("该车辆已被手机号为："+phone+"车主绑定！");
                   return rsp;
               }
            }

            if(appCars.size()>3){
                rsp.setStrError("添加的车辆已达上限!");
                return rsp;
            }
            AppCar car = VoPoConverter.copyProperties(req,AppCar.class);
            car.setCreateTime(new Date());
            car.setId(null);
            car.setUserId(usersWechat.getId());
            appCarMapper.insertAppCar(car);
            appUserCarMapper.insertUserCar(usersWechat.getUserId(), car.getId());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("添加成功!");
        } catch (Exception e) {
            rsp.setStrError("添加失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp editCar(AppAdCarReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            if(StringUtils.isBlank(req.getPlate())|| UnifiedUtils.integerIsNull(req.getId())){
                rsp.setStrError("参数不能为空!");
                return rsp;
            }
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            AppCar ap =  appCarMapper.getByPlateAndId(req.getPlate(),req.getId());
            if(ap!=null){
                String mobile = appCarMapper.getPlateByMobile(ap.getId());
                if(mobile!=null){
                    String phone = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
                    rsp.setStrError("该车辆已被手机号为："+phone+"车主绑定！");
                    return rsp;
                }
            }
            AppCar appCar = appCarMapper.getById(req.getId());
            if(appCar!=null){
                if(!req.getPlate().equals(appCar.getPlate())){
                    List<AppCar> appCars = appUserCarMapper.getCarByUserId(usersWechat.getUserId());
                    if(appCars!=null){
                        for(AppCar c:appCars){
                            if(req.getPlate().equals(c.getPlate())){
                                rsp.setStrError("您已经添加过该车辆!");
                                return rsp;
                            }
                        }
                    }
                }
                appCar = VoPoConverter.copyProperties(req,AppCar.class);
                appCarMapper.updateAppCarById(appCar);
                rsp.setResult(WechatBusinessRsp.SUCCESS);
                rsp.setStrError("修改成功!");
            }else {
                rsp.setStrError("车辆信息不存在!");
            }
        } catch (Exception e) {
            rsp.setStrError("修改失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findCarList(AppBusinessReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(usersWechat.getUserId());
            List<AppCarRsp> rsps = new ArrayList<>();
            for(AppCar c:appCars){
                rsps.add(new AppCarRsp(c.getId(),c.getPlate()));
            }
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setData(rsps);
            rsp.setStrError("查询成功");
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp deleteAppCar(AppCarReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            if(UnifiedUtils.integerIsNull(req.getId())){
                rsp.setStrError("参数不能为空!");
                return rsp;
            }
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            appCarMapper.deleteAppCarById(req.getId());
            appUserCarMapper.deleteByUserIdAndCarId(usersWechat.getUserId(),req.getId());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("删除成功");
        } catch (Exception e) {
            rsp.setStrError("删除失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findAppCarById(Integer id, String opendId) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            if(UnifiedUtils.integerIsNull(id)){
                rsp.setStrError("参数不能为空!");
                return rsp;
            }
            UsersWechat usersWechat = usersWechatMapper.getByOpenid(opendId);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            AppCar car = appCarMapper.getById(id);
            if(car!=null){
                if(StringUtils.isNotBlank(car.getCheckTime())){
                    car.setCheckTime(DateUtil.formatTime(car.getCheckTime()));
                }
                if(StringUtils.isNotBlank(car.getRegisterTime())){
                    car.setRegisterTime(DateUtil.formatTime(car.getRegisterTime()));
                }
            }
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("查询成功");
            rsp.setData(car);
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findUserInfo(AppBusinessReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            WechatUserInfoRsp infoRsp = VoPoConverter.copyProperties(usersWechat,WechatUserInfoRsp.class);
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(usersWechat.getUserId());
            List<String> strs = new ArrayList<>();
            for(AppCar car:appCars){
                strs.add(car.getPlate());
            }
            infoRsp.setPlates(strs);
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("查询成功");
            rsp.setData(infoRsp);
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findUserParkingInfo(String openId) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        //用户是否存在
        UsersWechat usersWechat = usersWechatMapper.getByOpenid(openId);
        List<CarRsp> carRsps = new ArrayList<>();
        if(usersWechat != null){
            //获取车辆信息
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(usersWechat.getUserId());
            List<AppUserPay> pays = appUserPayMaper.selectAppUserPayByUserId(usersWechat.getUserId());
            for(AppUserPay pay:pays){
                AppCar ac = new AppCar();
                ac.setPlate(pay.getPlate());
                appCars.add(ac);
            }
            if(appCars!=null&&appCars.size()!=0){
                for(AppCar car:appCars){
                    InParking inParking = inParkingMapper.getByPlate(car.getPlate());
                    if(inParking!=null){
                        GetFeeReq getFeeReq = new GetFeeReq();
                        getFeeReq.setParkingId(inParking.getParkingId());
                        getFeeReq.setPlate(car.getPlate());
                        getFeeReq.setToken(token);
                        String json = JSON.toJSONString(getFeeReq);
                        CarRsp carRsp = new CarRsp();
                        //获取费用
                        String result = HttpUtils.postJson(GETFEE_URL,json);
                        if(result!=null) {
                            GetFeeRsp getFeeRsp = JSON.parseObject(result, GetFeeRsp.class);
                            if (getFeeRsp.getActualFee() != getFeeRsp.getFee()) {
                                feeGroupMapper.updateLocalFeeGroupFee(getFeeRsp.getOrderId(), getFeeRsp.getActualFee());
                            }
                            carRsp = VoPoConverter.copyProperties(getFeeRsp,CarRsp.class);
                        }else {
                            carRsp.setResult(0);
                            carRsp.setPlate(car.getPlate());
                            carRsp.setStrError("网络超时！");
                        }
                        carRsp.setPrimaryInTime(DateUtil.formatDate(inParking.getPrimaryInTime(), "yyyy-MM-dd HH:mm:ss"));
                        carRsps.add(carRsp);
                    }else {
                        CarRsp carRsp = new CarRsp();
                        carRsp.setResult(0);
                        carRsp.setPlate(car.getPlate());
                        carRsp.setStrError("车辆未入场，未查询到车辆信息！");
                        carRsps.add(carRsp);
                    }
                }
            }
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setOpenid(usersWechat.getOpenid());
            rsp.setData(carRsps);
        }else {
            rsp.setStrError("用户未注册");
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findWechatGetFee(String openId, String plate) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            rsp.setResult(WechatBusinessRsp.FAIL);
            if(StringUtils.isBlank(plate)){
                rsp.setStrError("参数不能为空!");
                return rsp;
            }
            log.info("根据车牌获取支付费用，车牌号{}",plate);
            InParking inParking = inParkingMapper.getByPlate(plate);
            if(inParking!=null){
                GetFeeReq getFeeReq = new GetFeeReq();
                getFeeReq.setParkingId(inParking.getParkingId());
                getFeeReq.setPlate(plate);
                getFeeReq.setToken(token);
                String json = JSON.toJSONString(getFeeReq);
                //获取费用
                String result = HttpUtils.postJson(GETFEE_URL,json);
                GetFeeRsp getFeeRsp = JSON.parseObject(result, GetFeeRsp.class);
                CarRsp carRsp = VoPoConverter.copyProperties(getFeeRsp,CarRsp.class);
                carRsp.setPrimaryInTime(DateUtil.formatDate(inParking.getPrimaryInTime(), "yyyy-MM-dd HH:mm:ss"));
                rsp.setData(carRsp);
                rsp.setResult(WechatBusinessRsp.SUCCESS);

                /*AppUserPay pay = appUserPayMaper.getByPlateAndUserId(usersWechat.getUserId(),plate);
                AppCar appCar = appUserCarMapper.getCarByUserIdAndPlate(usersWechat.getUserId(),plate);
                if(pay==null&&appCar==null){
                    List<AppUserPay> pays = appUserPayMaper.selectAppUserPayByUserId(usersWechat.getUserId());
                    if(pays!=null&&pays.size()>3){
                        appUserPayMaper.deleteAppUserPayById(pays.get(0).getId());
                    }
                    pay = new AppUserPay();
                    pay.setCreateTime(new Date());
                    pay.setUserId(usersWechat.getUserId());
                    pay.setPlate(plate);
                    appUserPayMaper.insertAppUserPay(pay);
                }*/
            }else {
                rsp.setResult(WechatBusinessRsp.FAIL);
                rsp.setStrError("车辆未入场，未查询到车辆信息！");
            }
            log.info("是否存在路测车场未收费的订单");
            rsp.setRoad(getRoadParkingPayroad(plate,5));
            rsp.setOpenid(openId);
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findUseCoupon(String opedId,String plate,Integer parkingId) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            UserIssueRecordReq req = new UserIssueRecordReq();
            //根据车牌号获取车主的手机号
            String moblie = appUserCarService.selectByPlate(plate);
            List<MerchantCouponVo> merchantCouponVoList = new ArrayList<MerchantCouponVo>();
            if (StringUtils.isNotEmpty(moblie)) {
                req.setPlate(plate);
                req.setPhone(moblie);
                req.setParkingId(parkingId);
                req.setEndTime(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                //查询用户在当前车场可用的优惠券
                List<MerchantCoupon> merchantCouponList = merchantCouponMapper.selectByMobile(req);
                for (MerchantCoupon merchantCoupon : merchantCouponList) {
                    MerchantCouponVo merchantCouponVo = new MerchantCouponVo();
                    merchantCouponVo.setId(merchantCoupon.getId());
                    merchantCouponVo.setStatus(merchantCoupon.getStatus());
                    merchantCouponVo.setCreatedTime(DateUtil.formatDate(merchantCoupon.getCreatedTime(), "yyyy-MM-dd"));
                    if (merchantCoupon.getCouponType() != null) {
                        merchantCouponVo.setCouponType(merchantCoupon.getCouponType());
                    }
                    merchantCouponVo.setDiscount(merchantCoupon.getDiscount());
                    if (merchantCoupon.getFreeAmount() != null) {
                        merchantCouponVo.setFreeAmount(merchantCoupon.getFreeAmount());
                    }
                    if (merchantCoupon.getFreeHours() != null) {
                        merchantCouponVo.setFreeHours(merchantCoupon.getFreeHours());
                    }
                    merchantCouponVo.setParkingId(merchantCoupon.getParkingId());
                    merchantCouponVo.setUseWay(merchantCoupon.getUseWay());
                    merchantCouponVo.setParkingName(merchantCoupon.getParkingName());
                    merchantCouponVo.setEndTime(DateUtil.formatDate(merchantCoupon.getEndTime(), "yyyy-MM-dd"));
                    merchantCouponVoList.add(merchantCouponVo);
                }
            }
            rsp.setData(merchantCouponVoList);
            rsp.setResult(WechatRegRsp.SUCCESS);
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("获取车主优惠券列表异常！");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp merchantTransfer(String ids, String phone) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        if(StringUtils.isBlank(ids)||StringUtils.isBlank(phone)){
            rsp.setStrError("必填参数不能为空");
            return rsp;
        }
             //获取优惠券信息
        String strs[] = ids.split(",");
        for(String s:strs) {
           Integer id = Integer.parseInt(s);
           MerchantCoupon coupon = merchantCouponMapper.getById(id);
           if (coupon == null) {
              rsp.setStrError("未获取到优惠券信息");
              return rsp;
           }
           log.info("转赠优惠券成功优惠券id({})转赠的手机号({})"+id,phone);
           merchantCouponMapper.updateMerchantByMobile(id, phone);
           rsp.setResult(WechatBusinessRsp.SUCCESS);
           rsp.setStrError("转赠成功!");
           }
        return rsp;
    }

    @Override
    public WechatRegRsp inOutParkingQuery(WechatInOutParkingReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            if(StringUtils.isBlank(req.getPlates())){
                rsp.setResult(WechatBusinessRsp.FAIL);
                rsp.setStrError("车牌号不能为空！");
                return rsp;
            }
            if(StringUtils.isNotBlank(req.getInTime())){
                req.setInTime(req.getInTime()+" 00:00:00");
            }else {
                req.setInTime(DateUtil.getFirstDay()+" 00:00:00");
            }
            if(StringUtils.isNotBlank(req.getOutTime())){
                req.setOutTime(req.getOutTime()+" 23:59:59");
            }else {
                req.setOutTime(DateUtil.formatCurrentTime("yyyy-MM-dd HH:mm:ss"));
            }
            PageHelper.startPage(req.getStart(), req.getEnd());
            List<InOutParkingRsp> parkingRsps = inOutParkingMapper.selectInOutParkingRecord(req.getPlates(),req.getInTime(),req.getOutTime(),req.getStaMoney(),req.getEndMoney());
            PageInfoBT pib = new PageInfoBT(parkingRsps);
            rsp.setData(pib.getRows());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("查询成功!");
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findStopParkingRecord(InvoiceReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            if(StringUtils.isNotBlank(req.getStaTime())){
                req.setStaTime(req.getStaTime()+" 00:00:00");
            }else {
                req.setStaTime(DateUtil.getFirstDay()+" 00:00:00");
            }
            if(StringUtils.isNotBlank(req.getEndTime())){
                req.setEndTime(req.getEndTime()+" 23:59:59");
            }else {
                req.setEndTime(DateUtil.formatCurrentTime("yyyy-MM-dd HH:mm:ss"));
            }
            //获取发票信息
            List<String> plates = new ArrayList<>();
            AppBusinessReq appBusinessReq = new AppBusinessReq();
            appBusinessReq.setOpendId(req.getOpenid());
            appBusinessReq.setPhone(req.getPhone());
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(appBusinessReq);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            User user = userMapper.getById(usersWechat.getUserId());
            if(user == null){
                rsp.setStrError("身份验证失败,请重新登录。");
                return rsp;
            }
            List<AppCar> cars = appUserCarMapper.getCarByUserId(user.getId());
            if (cars == null||cars.size()==0) {
                rsp.setStrError("没有车辆请绑定车辆！");
                return rsp;
            }
            for(AppCar car:cars){
                plates.add(car.getPlate());
            }
            List<InOutParkingRsp> parkingRsps = new ArrayList<>();
            //获取出入记录
            List<InOutParkingRsp> list = new ArrayList<>();
            List<InOutParkingRsp> inOutParkingRsps = new ArrayList<>();
            if(req.getType()==1){
                //获取可开发票信息
                parkingRsps = inOutParkingMapper.selectInOutParkingRecordList(plates,req.getStaTime(),req.getEndTime());
                List<String> list1 = new ArrayList<>();
                for(InOutParkingRsp iop:parkingRsps){
                    if(iop!=null) {
                        if(StringUtils.isNotBlank(iop.getStopTime())){
                            iop.setStopTime(Integer.parseInt(iop.getStopTime())+"");
                        }
                        iop.setType(1);
                        list1.add(iop.getRecordOrderId());
                        inOutParkingRsps.add(iop);
                    }
                }
                if(list1.size()>0){
                    List<PayOrder> payOrderList = payOrderMapper.getRecordOrderId(list1);
                    for (int i = 0; i < payOrderList.size(); i++) {
                        PayOrder payOrder = payOrderList.get(i);
                        for (int j = 0; j < inOutParkingRsps.size(); j++){
                            InOutParkingRsp inOutParkingRsp = inOutParkingRsps.get(j);
                            int compare = payOrder.getRecordOrderId().compareTo(inOutParkingRsp.getRecordOrderId());
                            if(compare ==0){
                                inOutParkingRsp.setActualFee(payOrder.getFee());
                                inOutParkingRsp.setPayorderId(payOrder.getId());
                                InOutParkingRsp inOutParkingRspTemp = new InOutParkingRsp();
                                BeanUtils.copyProperties(inOutParkingRsp,inOutParkingRspTemp);
                                list.add(inOutParkingRspTemp);
                                //一个InOutParking记录有可能对应多个payorder记录 一对多关系 一个payorder记录对应一个InOutParking记录
                                break;
                            }
                        }
                    }
                }
            }else {
                list = getInOutParking(inOutParkingMapper.selectInOutParkingRecordOtherList(plates,req.getStaTime(),req.getEndTime()));
            }
            log.info("可开发票数量:{}",list.size());
            List<InOutParkingRsp> rsps = PageUtil.startPage(list,req.getPageNum(),req.getPageSize());
            rsp.setData(rsps);
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("查询成功!");
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findInvoiceHistory(InvoiceReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            if(StringUtils.isNotBlank(req.getStaTime())){
                req.setStaTime(req.getStaTime()+" 00:00:00");
            }
            if(StringUtils.isNotBlank(req.getEndTime())){
                req.setEndTime(req.getEndTime()+" 23:59:59");
            }
            //获取发票信息
            List<String> plates = new ArrayList<>();
//            User user = checkParam.getUserByOpenid(req.getOpenid());
            AppBusinessReq appBusinessReq = new AppBusinessReq();
            appBusinessReq.setOpendId(req.getOpenid());
            appBusinessReq.setPhone(req.getPhone());
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(appBusinessReq);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            User user = userMapper.getById(usersWechat.getUserId());
            if(user == null){
                rsp.setStrError("身份验证失败,请重新登录。");
                return rsp;
            }
            List<AppCar> cars = appUserCarMapper.getCarByUserId(user.getId());
            if (cars == null||cars.size()==0) {
                rsp.setStrError("没有车辆请绑定车辆！");
                return rsp;
            }
            for(AppCar car:cars){
                plates.add(car.getPlate());
            }
            PageHelper.startPage(req.getPageNum(), req.getPageSize());
            List<PiaoTong> piaoTongs = piaoTongMapper.selectPiaoTongListByPlate(plates);
            rsp.setData(piaoTongs);
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("查询成功!");
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findUserInvoiceHistory(AppBusinessReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            List<UserInvoice> invoices = userInvoiceMapper.selectUserInvoiceListByUserId(usersWechat.getUserId());
            rsp.setOpenid(usersWechat.getOpenid());
            rsp.setData(invoices);
            rsp.setResult(WechatBusinessRsp.SUCCESS);
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp deleteUserInvoice(AppBusinessReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(req);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            userInvoiceMapper.deleteUserInvoiceById(req.getId());
            rsp.setOpenid(usersWechat.getOpenid());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("删除成功!");
        } catch (Exception e) {
            rsp.setStrError("删除失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp recharge(WechatCarRechargeReq req) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            UsersWechat usersWechat = usersWechatMapper.getByOpenid(req.getOpenid());
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }

            Date date = new Date();
            // 保存订单
            log.info("-------保存微信用户月卡充值完成订单！--------");
            PayOrder payOrder = new PayOrder();
            payOrder.setPlate(req.getPlate());
            payOrder.setOpenid(req.getOpenid());
            payOrder.setFee(req.getFee());
            payOrder.setOrderNo(req.getOrderNo());
            payOrder.setTransactionId(req.getTransactionId());
            payOrder.setParkingId(req.getParkingId());
            payOrder.setFeeType(PayOrder.FEETYPE_RECHARGE);
            payOrder.setCreatedTime(date);
            payOrder.setTradeType(PayOrder.TRADETYPE_WECHAT);
            payOrder.setPayWay(PayOrder.PAY_WAY_WECHAT);
            payOrder.setPayStatus(PayOrder.PAY_UNKNOWN);
            payOrder.setPayTime(date);
            payOrder.setMonth(req.getMonth());

            payOrder.setInfoType(PayOrder.INFOTYPE_FEEDETAIL);
            payOrderMapper.insertPayOrder(payOrder);
            // 加入消息队列中，准备下发车场
            PayOrderMessageList.addPayOrderMessage(payOrder);
            rsp.setData(payOrder.getOrderNo());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("查询成功!");
        } catch (Exception e) {
            rsp.setStrError("查询失败!");
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public WechatRegRsp findRoadPayOrderList(String openId, String phone,Integer type) {
        WechatRegRsp rsp = new WechatRegRsp();
        try {
            User user = null;
//            根据openid获取用户id
            if(StringUtils.isNotBlank(phone)){
                user = userMapper.getByMobile(phone);
            }else {
                UsersWechat usersWechat = usersWechatMapper.getByOpenid(openId);
                if (usersWechat == null) {
                    rsp.setResult(AppBusinessRsp.FAIL);
                    rsp.setStrError("获取用户信息失败!");
                    return rsp;
                }
                user = userMapper.getById(usersWechat.getUserId());
            }
            if (user != null) {
                 //获取用户关联的车牌号
                List<RoadPayOrderVo> list = new ArrayList<>();
                List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
                for(AppCar c:appCars){
                    List<RoadPayOrderVo> payOrders = payOrderMapper.selectRoadPayOrderList(c.getPlate(),type);
                    for(RoadPayOrderVo vo : payOrders){
                        long time = DateUtil.parseDate(vo.getLeaveTime(),"yyyy-MM-dd HH:mm:ss").getTime()-DateUtil.parseDate(vo.getEnterTime(),"yyyy-MM-dd HH:mm:ss").getTime();
                        vo.setStopTime(DateUtil.formatTimeNoZero(time));
                        vo.setLeaveTime(DateUtil.formatDateWithoutMillisecond(vo.getLeaveTime()));
                        vo.setEnterTime(DateUtil.formatDateWithoutMillisecond(vo.getEnterTime()));
                        if(StringUtils.isNotBlank(vo.getLeaveUrl())){
                            String [] s = vo.getLeaveUrl().split(",");
                            List<String> imgList = new ArrayList<>();
                            for(String str :s){
                                imgList.add(str);
                            }
                            vo.setLeaveImg(imgList);
                        }
                        if(StringUtils.isNotBlank(vo.getEntreUrl())){
                            String [] s = vo.getEntreUrl().split(",");
                            List<String> imgList = new ArrayList<>();
                            for(String str :s){
                                imgList.add(str);
                            }
                            vo.setEntreImg(imgList);
                        }
                        list.add(vo);
                    }
                }
                //进行分组
                List<ParkingGroup> groups = new ArrayList<ParkingGroup>();
                ParkingGroup group = null;
                String address = "";
                int i = 0;
                List<RoadPayOrderVo> orderVos = new ArrayList<>();
                for(RoadPayOrderVo vo :list){
                    i++;
                    if(group==null){
                        group = new ParkingGroup();
                        group.setParkingId(vo.getParkingId());
                        Parking p =parkingMapper.getParkingById(vo.getParkingId());
                        if(p!=null){
                            address = p.getAddress();
                            group.setParkingName(p.getName());
                        }
                    }
                    vo.setAddress(address);
                    if(group.getParkingId().equals(vo.getParkingId())){
                        orderVos.add(vo);
                    }else {
                        group.setOrderVos(orderVos);
                        groups.add(group);
                        group = new ParkingGroup();
                        group.setParkingId(vo.getParkingId());
                        Parking p =parkingMapper.getParkingById(vo.getParkingId());
                        if(p!=null){
                            address = p.getAddress();
                            group.setParkingName(p.getName());
                        }
                        orderVos = new ArrayList<>();
                        orderVos.add(vo);
                    }
                    if(i==list.size()){
                        group.setOrderVos(orderVos);
                        groups.add(group);
                    }
                }
                rsp.setData(groups);
                rsp.setResult(WechatBusinessRsp.SUCCESS);
                rsp.setStrError("查询成功!");
            }else {
                rsp.setData(new ArrayList<>());
                rsp.setResult(WechatBusinessRsp.FAIL);
                rsp.setStrError("未查找到用户信息！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取路测订单列表异常{}", e.getMessage());
        }
        return rsp;
    }

        private List<ParkingGroup> getRoadParkingPayroad(String plate,Integer type){
            List<ParkingGroup> groups = new ArrayList<ParkingGroup>();
            try {
                //获取用户关联的车牌号
                List<RoadPayOrderVo> list = new ArrayList<>();
                    List<RoadPayOrderVo> payOrders = payOrderMapper.selectRoadPayOrderList(plate,type);
                    for(RoadPayOrderVo vo : payOrders){
                        long time = DateUtil.parseDate(vo.getLeaveTime(),"yyyy-MM-dd HH:mm:ss").getTime()-DateUtil.parseDate(vo.getEnterTime(),"yyyy-MM-dd HH:mm:ss").getTime();
                        vo.setStopTime(DateUtil.formatTimeNoZero(time));
                        vo.setLeaveTime(DateUtil.formatDateWithoutMillisecond(vo.getLeaveTime()));
                        vo.setEnterTime(DateUtil.formatDateWithoutMillisecond(vo.getEnterTime()));
                        if(StringUtils.isNotBlank(vo.getLeaveUrl())){
                            String [] s = vo.getLeaveUrl().split(",");
                            List<String> imgList = new ArrayList<>();
                            for(String str :s){
                                imgList.add(str);
                            }
                            vo.setLeaveImg(imgList);
                        }
                        if(StringUtils.isNotBlank(vo.getEntreUrl())){
                            String [] s = vo.getEntreUrl().split(",");
                            List<String> imgList = new ArrayList<>();
                            for(String str :s){
                                imgList.add(str);
                            }
                            vo.setEntreImg(imgList);
                        }
                        list.add(vo);
                    }
                //进行分组
                ParkingGroup group = null;
                String address = "";
                int i = 0;
                List<RoadPayOrderVo> orderVos = new ArrayList<>();
                for(RoadPayOrderVo vo :list){
                    i++;
                    if(group==null){
                        group = new ParkingGroup();
                        group.setParkingId(vo.getParkingId());
                        Parking p =parkingMapper.getParkingById(vo.getParkingId());
                        if(p!=null){
                            address = p.getAddress();
                            group.setParkingName(p.getName());
                        }
                    }
                    vo.setAddress(address);
                    if(group.getParkingId().equals(vo.getParkingId())){
                        orderVos.add(vo);
                    }else {
                        group.setOrderVos(orderVos);
                        groups.add(group);
                        group = new ParkingGroup();
                        group.setParkingId(vo.getParkingId());
                        Parking p =parkingMapper.getParkingById(vo.getParkingId());
                        if(p!=null){
                            address = p.getAddress();
                            group.setParkingName(p.getName());
                        }
                        orderVos = new ArrayList<>();
                        orderVos.add(vo);
                    }
                    if(i==list.size()){
                        group.setOrderVos(orderVos);
                        groups.add(group);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取路测订单列表异常{}", e.getMessage());
            }
            return groups;
        }



    @Override
    public WechatRegRsp roadPayOrderMerge(String openId, String orderNos) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {

            //根据订单号获取所有订单
            if(StringUtils.isNotBlank(orderNos)){
                String str [] = orderNos.split(",");
                if(str.length>1){
                    PayOrder pay = new PayOrder();
                    List<Integer> list = new ArrayList<>();
                    List<PayOrder> payOrders = new ArrayList<>();
                    for(String s : str){
                        PayOrder payOrder = payOrderMapper.getByOrderNo(s);
                        list.add(payOrder.getParkingId());
                        payOrders.add(payOrder);
                    }
                    int actualFee = 0;    // 实收费用
                    int couponFee = 0;    // 优惠费用
                    int fee = 0;
                    int shouldFee = 0; //应收费用
                    for(PayOrder p:payOrders){
                        for(Integer id:list){
                            if(p.getParkingId() != id){
                                rsp.setStrError("不能跨车场合并订单");
                                return rsp;
                            }
                        }
                        pay = p;
                        actualFee = actualFee + p.getActualFee();
                        couponFee = couponFee + p.getCouponFee();
                        fee = fee + p.getFee();
                        shouldFee = shouldFee + p.getShouldFee();
                    }
                    // 订单保存到数据库
                    PayOrder payOrder = new PayOrder();
                    payOrder.setInfoId(pay.getParkingId());
                    payOrder.setInfoType(PayOrder.INFOTYPE_INPARKING);
                    payOrder.setFee(fee);
                    payOrder.setDeviceId(0);
                    payOrder.setSend(1);
                    Date curTime = new Date();
                    String orderNo = PayUtil.getOrderNo(pay.getParkingId(), curTime);
                    payOrder.setOrderNo(orderNo);
                    payOrder.setPlate(pay.getPlate());
                    payOrder.setOutTime(pay.getOutTime());
                    payOrder.setCreatedTime(curTime);
                    payOrder.setParkingId(pay.getParkingId());
                    payOrder.setTradeType(PayOrder.TRADETYPE_UNKNOWN);
                    payOrder.setPayWay(PayOrder.PAY_WAY_UNKNOWN);
                    payOrder.setPayStatus(PayOrder.PAYSTATUS_UNKNOWN);
                    payOrder.setNpsMAccountId(pay.getNpsMAccountId());
                    payOrder.setApiUserId(pay.getApiUserId());
                    payOrder.setCouponFee(couponFee);
                    payOrder.setShouldFee(shouldFee);
                    payOrder.setCardFee(0);
                    payOrder.setDiscountFee(0);
                    payOrder.setFreeFee(0);
                    payOrder.setLocalFeegroupId(pay.getLocalFeegroupId());
                    payOrder.setRecordOrderId(pay.getRecordOrderId());
                    payOrder.setFeeEndTime(pay.getFeeEndTime());
                    payOrder.setCouponId(0);
                    payOrder.setServiceFee(0);
                    payOrder.setFeeType(PayOrder.FEETYPE_SELF);
                    payOrder.setPiType(1);
                    payOrderMapper.insertPayOrderMerge(payOrder);
                    for(String s : str){
                        PayOrderMerge merge = new PayOrderMerge();
                        merge.setOrderNo(orderNo);
                        merge.setCreatedTime(curTime);
                        merge.setMergeOrderNo(s);
                        merge.setPayStatus(0);
                        payOrderMergeMapper.insertPayOrderMerge(merge);
                    }
                    rsp.setResult(WechatBusinessRsp.SUCCESS);
                    rsp.setData(orderNo);
                }else {
                    PayOrder payOrder = payOrderMapper.getByOrderNo(str[0]);
                    rsp.setResult(WechatBusinessRsp.SUCCESS);
                    rsp.setData(payOrder.getOrderNo());
                }
            }else {
                rsp.setStrError("订单号不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rsp;
    }

    private List<InOutParkingRsp> getInOutParking(List<InOutParkingRsp> parkingRsps){
        List<InOutParkingRsp> list = new ArrayList<>();
        for(InOutParkingRsp iop:parkingRsps){
            if(iop!=null){
                if(StringUtils.isNotBlank(iop.getStopTime())){
                    iop.setStopTime(Integer.parseInt(iop.getStopTime())/60+"");
                }
                iop.setType(3);
                Integer num = feeDetailMapper.getPaymentAmount(iop.getLocalInoutparkingId(),iop.getParkingId());
                if(num==null){
                    num =0;
                }
                //0元属于异常订单
                if(num!=0){
                    //车场是否是有权限开通发票
                    PiaotongPark park = piaoTongMapper.getTaxpayerNumAndTaxRateByParkingId(iop.getParkingId());
                    if(park != null){
                        PiaoTong piaoTong = piaoTongMapper.selectPiaoTongByInoutParkingId(iop.getParkingId(),iop.getLocalInoutparkingId());
                        if(piaoTong!=null) {
                            iop.setType(2);
                        }else {
                            continue;
                        }
                    }
                }
                iop.setActualFee(num);
                list.add(iop);
            }
        }
        return list;
    }

    @Override
    public WechatRegRsp deletePiaotongInvoice(String phone, String openId, Integer id) {
        WechatRegRsp rsp = new WechatRegRsp();
        rsp.setResult(WechatBusinessRsp.FAIL);
        try {
            AppBusinessReq appBusinessReq = new AppBusinessReq();
            appBusinessReq.setPhone(phone);
            appBusinessReq.setOpendId(openId);
            UsersWechat usersWechat = usersWechatMapper.getByOpenidAndPhone(appBusinessReq);
            if(usersWechat == null){
                rsp.setStrError("身份验证失败,请重新登录!");
                return rsp;
            }
            piaoTongMapper.deletePiaotongInvoiceById(id);
            rsp.setOpenid(usersWechat.getOpenid());
            rsp.setResult(WechatBusinessRsp.SUCCESS);
            rsp.setStrError("删除成功!");
        } catch (Exception e) {
            rsp.setStrError("删除失败!");
            e.printStackTrace();
        }
        return rsp;
    }
}
